<template>
  <div class="attachForm">
    <el-upload
      ref="upload"
      action="#"
      :on-change="changeFile"
      :file-list="newUploadObj.files"
      name="fileList"
      :class="{
        attachFormUpload: newUploadObj.files.length,
        hideClass: disabled,
      }"
      class="attachLine"
      :auto-upload="false"
      :accept="acceptType"
      :limit="limit"
      :on-exceed="onExceed"
      :multiple="multiple"
    >
      <!-- <el-button slot="trigger" size="mini" type="primary" v-if="!disabled">选取文件</el-button> -->
      <el-button slot="trigger" icon="el-icon-paperclip" size="mini" type="text" v-if="!disabled">添加附件</el-button>
      <div slot="tip" class="attach-form_tip" v-if="title && !disabled">
        Tip: {{ title }}
      </div>
      <div slot="file" slot-scope="{ file }">
        <p class="file-boder">
          {{ file.name }}
          <span class="upload-btn-in">
            <el-button
              type="text"
              size="mini"
              icon="el-icon-zoom-in"
              v-if="file.id"
              @click="preFile(file)"
              title="预览"
            ></el-button>
            <el-button
              type="text"
              size="mini"
              icon="el-icon-download"
              v-if="file.id"
              @click="downloadFile(file)"
              title="下载"
            ></el-button>
            <el-button
              type="text"
              size="mini"
              icon="el-icon-delete"
              @click="removeFile(file)"
              title="移除"
              v-if="!disabled && !isDelete"
            ></el-button>
            <el-button
              type="text"
              size="mini"
              icon="el-icon-delete"
              @click="deleteFile(file)"
              title="删除"
              v-if="!disabled && isDelete"
            ></el-button>
          </span>
        </p>
      </div>
    </el-upload>
    <dialogPublic
      :title="'文件预览'"
      :show.sync="showPreview"
      appendTobody
      fullscreen
      noFootBtn
      @doClose="() => (showPreview = false)"
    >
      <preview :fileObj="currentAttach" v-if="showPreview"></preview>
    </dialogPublic>
  </div>
</template>
<script>
// 导入组件
import preview from "@/components/attach/preview";
import {
  uploadAttach, //附件上传
  deleteFiles, //删除单个附件通过文件id
  getAttachList, //附件列表获取
} from "@/api/common";
export default {
  props: {
    /**
     * 文件列表
     * 数据格式[{name: '文件名', url:'文件地址'}]
     */
    filesList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    /* 是否立即删除 */
    isDelete: {
      type: Boolean,
      default: false,
    },
    //支持上传的文件类型['doc','pdf','png']
    accept: {
      type: Array,
      default: () => {
        return [];
      },
    },
    //最大允许上传个数
    limit: {
      type: Number,
      default: null,
    },
    //是否支持多选
    multiple: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "",
    },
    rules: null,
  },
  components: { preview },

  data() {
    return {
      newUploadObj: {
        deleteId: [],
        files: [],
      },
      showViewer: false, // 显示查看器
      showPreview: false, //pdf显示器
      showPdf: false,
      preurl: "", //预览URL
      htmlText: "预览转换中...",
      //文件分类
      typeObj: {
        imge: ["jpg", "jpeg", "gif", "bmp", "png"],
        pdf: ["pdf"],
        video: ["mp4", "m2v", "mkv", "rmvb", "wmv", "avi", "flv", "mov", "m4v"],
        html: ["htm", "html"],
        docx: ["doc", "docx", "docm", "dotx", "dotm"],
        xlsx: ["xls", "xlsx", "xlsm", "xltx", "xltm", "xlsb", "xlam"],
        // txt:["txt"],
        pptx: ["ppt", "pptx", "pot", "potx", "pptm", "ppsx", "ppsm"],
        zip: ["zip", "rar", "7z", "7-zip", "tar", "gzip", "bz2", "jar"],
      },
    };
  },
  created() {
    this.init();
  },
  computed: {
    acceptType() {
      return this.accept.join();
    },
  },
  watch: {
    "newUploadObj.files": {
      handler(val) {
        let { deleteId, files } = this.newUploadObj;
        let filesObj = { deleteId, files };
        this.$emit("changeFilesField", filesObj);
      },
      deep: true,
    },
    filesList: {
      handler(val) {
        if (val.length && val[0] != "ok") {
          this.init();
        }
      },
      deep: true,
    },
  },
  methods: {
    init() {
      this.newUploadObj.files = this.filesList;
    },
    removeFile(file) {
      let arr = this.newUploadObj.files.filter((i) => {
        return i.uid != file.uid;
      });
      this.newUploadObj.files = arr || [];
      if (file.id) {
        this.newUploadObj.deleteId.push(`${file.id}`);
      }
    },
    deleteFile(data) {
      this.$confirm("此操作将删除【" + data.name + "】, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteFiles(data.id)
            .then((res) => {
              this.getFileList();
              this.$message.success("文件删除成功！");
            })
            .catch((e) => {
              this.$message.warning("文件删除失败！");
            });
        })
        .catch((e) => {});
    },
    changeFile(file, fileList) {
      if (this.beforeUpload(file.raw, fileList)) {
        this.newUploadObj.files.push(file.raw);
      } else {
        fileList.map((i, index) => {
          if (i.uid == file.uid) {
            this.$refs.upload.uploadFiles.splice(index, 1);
          }
        });
      }
    },
    //预览
    preFile(file) {
      let { extension, path } = file;
      let type = "";
      for (const key in this.typeObj) {
        //循环遍历typeObj
        let arr = this.typeObj[key];
        if (arr.includes(extension)) {
          //比较找到typeObj相应的后缀名，从而判断它属于哪个类型
          type = key;
        }
      }
      if (["imge", "pdf", "video", "html"].includes(type)) {
        this.currentAttach = file;
        this.showPreview = true;
      } else {
        this.$confirm(`该文件暂不支持预览，是否直接下载？`, "提示", {
          confirmButtonText: "立即下载",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.downloadFile(file);
        });
      }
    },
    //执行下载
    doDownload(res, fileName) {
      const blob = new Blob([res]);
      const url = window.URL.createObjectURL(blob);
      const elink = document.createElement("a");
      elink.download = fileName;
      elink.style.display = "none";
      elink.href = url;
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    },
    // 点击下载
    downloadFile(row) {
      // let path = process.env.BASEURL+'/eam/attachment/download/?fileId='+ row.id;
      let fileName = row.name;
      this.$utils.downloadFile(row.id, fileName);
    },
    //是否显示预览按钮
    showPreBtn(file) {
      let typeArr = ["jpg", "jpeg", "gif", "bmp", "png", "pdf"];
      if (file.id) {
        if (file.pdfUrl) {
          return true;
        } else {
          return typeArr.includes(file.extension);
        }
      } else {
        return false;
      }
    },
    onExceed(file, fileList) {
      this.$message.warning(
        "文件数量超过限制！最多只能上传" + this.limit + "个文件！"
      );
    },
    //选中文件上传前验证
    beforeUpload(file, fileList) {
      let typeArr = file.name.split(".");
      let type = typeArr[typeArr.length - 1];
      let isUpload = true;

      if (this.acceptType) {
        if (this.acceptType.indexOf(type) == -1) {
          this.$message.error("文件类型不符合！");
          isUpload = false;
        }
      }
      if (this.rules) {
        let rulesResult = this.rules(file, fileList);
        if (!rulesResult.success) {
          isUpload = false;
          this.$message.error(rulesResult.msg || "验证错误");
        }
      }
      return isUpload;
    },
    //返回的附件数据
    returnFilsObj() {
      let { deleteId, files } = this.newUploadObj;
      let filesObj = { deleteId, files };
      return filesObj;
    },
    //提交附件信息
    doSubmitFiles(id, type) {
      let { deleteId, files } = this.newUploadObj;
      let formData = new FormData();
      if (files.length != 0 || deleteId.length != 0) {
        files.map((i) => {
          if (!i.hasOwnProperty("id")) {
            formData.append("files", i);
          }
        });
        let form = {
          businessId: id,
          businessType: type,
          deleteFileIds: deleteId,
        };
        uploadAttach(form, formData)
          .then((res) => {
            this.$message.success("保存成功！");
          })
          .catch((res) => {
            this.$message.warning("文件上传失败,请重新上传！");
          });
      }
    },
    //获取附件列表数据
    getFileList(id, type) {
      let form = {
        businessId: id,
        businessType: type,
      };
      getAttachList(form).then((res) => {
        let data = res.data || [];
        this.newUploadObj.files = data;
      });
    },
  },
};
</script>
<style lang="less" scoped>
.upload-btn-in {
  position: absolute;
  right: 5px;
}
.file-boder {
  border: 1px dashed #ebebeb;
  padding: 0px 80px 0 10px !important
}
.attachFormUpload,
.attachLine {
  text-align: left;
}
.attachFormUpload .el-upload-list {
  margin-top: 10px;
  border: 1px solid #ebebeb;
  padding: 0 10px 10px 10px;
  text-align: left;
  border-radius: 4px;
}

.attach-form_tip {
  height: 30px;
  display: inline-block;
  font-size: 12px;
  color: #8a8a8a;
  line-height: 18px;
  margin-left: 10px;
}
.hideClass .el-upload {
  display: none;
}
.el-upload {
  // position: relative;
  // left: 0px;
}
</style>
